﻿using EWS;
using Microsoft.Exchange.WebServices.Data;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Common.WeChat;
using XF.Meeting.DAL;

namespace QuartzJob
{
    public class UpdateStateJobWithExchange : IJob
    {

        public System.Threading.Tasks.Task Execute(IJobExecutionContext context)
        {
            var dal = new MeetingDal();

            var aa = dal.UpdateMeeting_E(DateTime.Now, out DataTable dt, out string error);
            if (error == "")
            {
                var list1 = XF.Common.TableToList.ToList<meetIdS>(dt);
                if (list1.Count > 0)
                {
                    foreach (var item in list1)
                    {
                        var result = ChancelExchange(item);
                        SendWxMssage(item.ID, result, true);
                    }
                    return System.Threading.Tasks.Task.CompletedTask;
                }
                else
                {
                    return System.Threading.Tasks.Task.CompletedTask;
                }
            }
            return System.Threading.Tasks.Task.CompletedTask;

        }

        private bool ChancelExchange(meetIdS item)
        {
            var result = false;
            var dal = new ExchangeToDbDal();
            var meetList = dal.GetMeetExchangeItemIdByID(item.ID);
            foreach (var meet in meetList)
            {
                var roomService = ExChangeHelper.getExChangeHelper(5, meet.ewsAccount, meet.ewsPwd, meet.ewsUrl);
                roomService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, meet.OrderUser);
                //    ExChangeHelper.getExChangeHelper(item.Mail);
                var aaa = new ItemId(meet.ExchangeItemId);

                try
                {
                    Appointment oApt = Appointment.Bind(roomService, aaa, BasePropertySet.IdOnly);
                    oApt.Delete(DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendToAllAndSaveCopy);
                    result = true;
                }
                catch (Exception e)
                {
                    result = false;
                    continue;


                }
            }
            return result;





        }

        public static void SendWxMssage(int ID, bool exchangeResult, bool isTen = false)
        {
            var dal = new MeetingDal();
            var res = dal.GetCInfoByID(ID).Result;

            var list = XF.Common.TableToList.ToList<XF.Meeting.Entity.View.MeetingInfoSingle>(res);
            var meetingInfoSingle = list[0];
            meetingInfoSingle.date = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("yyyy-MM-dd");
            meetingInfoSingle.Begin = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("HH:mm");
            meetingInfoSingle.End = Convert.ToDateTime(meetingInfoSingle.EndTime).ToString("HH:mm");
            meetingInfoSingle.CRooms = meetingInfoSingle.CRoom + "," + meetingInfoSingle.CRooms;
            var msgList = dal.getMeetInfoAndUserPhone(ID, out string StrError);
            var phoneList = XF.Common.TableToList.ToList<meetIdS>(msgList.Tables[0]);
            var phone = phoneList.Select(i => i.Account).ToList();
            var userr = GetUserString(phone);
            var wx = new WeChatHelper();
            if (exchangeResult)
            {
                var msg = new Message(new Text($"{meetingInfoSingle.CoordinatorName}邀请您参加《{meetingInfoSingle.ConferenceTheme}》会议，时间 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}~{meetingInfoSingle.End}，地点：{meetingInfoSingle.CRooms}，主持人：{meetingInfoSingle.HostPersonName}，由于未签到，会议室该时间段已被释放。"), userr);
                wx.SendTextMessage(msg);
            }
            else
            {
                var msg = new Message(new Text($"{meetingInfoSingle.CoordinatorName}邀请您参加《{meetingInfoSingle.ConferenceTheme}》会议，时间 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}~{meetingInfoSingle.End}，地点：{meetingInfoSingle.CRooms}，主持人：{meetingInfoSingle.HostPersonName}，由于未签到请会议发起人：{meetingInfoSingle.CoordinatorName} 前往OUTLOOK中手动取消此事件。"), userr);
                wx.SendTextMessage(msg);
            }



            dal.updateWxState(ID, out string strError);


        }
        public static string GetUserString(List<string> userList)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in userList)
            {
                //if (string.IsNullOrWhiteSpace(RedisCache.Hash_Get<string>("UserPhone", item)))
                //{
                //    continue;
                //}

                sb.Append(item);
                sb.Append("|");
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
        public class meetIdS
        {
            public int ID { get; set; }
            public string Phone { get; set; }
            public string Account { get; set; }
            public string MasterItemId { get; set; }
            public string ExchangeItemId { get; set; }
            public int ItemSort { get; set; }
            public int Coordinator { get; set; }
            public string sourceType { get; set; }
            public string Mail { get; set; }
            public string RoomMail { get; set; }
        }

    }
}
